import { defineStore } from 'pinia'
import { ref } from 'vue'

interface UserInfo {
  id: number
  userAccount: string
  username: string
  userRole: number
  avatar: string | null
  phone: string
  email: string
  userStatus: number
  createTime: string
  updateTime: string
}

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref<UserInfo | null>(null)

  function initUserInfo() {
    const storedUserInfo = localStorage.getItem('userInfo')
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
    }
  }

  function setToken(newToken: string) {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  function setUserInfo(info: UserInfo) {
    userInfo.value = info
    localStorage.setItem('userRole', info.userRole.toString())
    localStorage.setItem('userInfo', JSON.stringify(info))
  }

  function logout() {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('userRole')
    localStorage.removeItem('userInfo')
  }

  initUserInfo()

  return {
    token,
    userInfo,
    setToken,
    setUserInfo,
    logout,
  }
})
